package com.cqc.jdk8.Jutil.concurrent.forkJoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author cui
 * @date 2025/6/22 21:39
 * @description  Recursive:递归
 **/
public class SumRecursiveTask extends RecursiveTask<Integer> {

    int[] array;
    int start;
    int end;
    int threshold = 500;

    public SumRecursiveTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        //检查任务是否足够小，如果是，则直接计算
        if ((end - start) <= threshold) {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        }
        //任务太大，一份味儿
        int middle = (start + end) / 2;
        SumRecursiveTask leftTask = new SumRecursiveTask(array, start, middle);
        leftTask.fork();
        SumRecursiveTask rightTask = new SumRecursiveTask(array, middle, end);
        rightTask.fork();
        //汇总结果
        return leftTask.join() + rightTask.join();
    }
}
